package com.tsd.core.job;

import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import com.alibaba.fastjson.JSON;
import com.tsd.core.annotation.TaskJob;
import com.tsd.core.annotation.TaskJobMethod;
import com.tsd.core.datasource.DataSourceUtils;
import com.tsd.core.datasource.SpringContextUtil;
import com.tsd.core.utils.ExceptionUtil;
import com.tsd.core.utils.HlpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;

import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: JobUtils
 * @Description: TODO
 * @Author: Hillpool
 * @Date: 2024/4/16 11:16
 * @Version: 1.0
 */
public class JobUtils {

    public static final Logger LOGGER = LoggerFactory.getLogger(JobUtils.class);

    public static boolean checkTable() {
        return false;
    }

    /**
     * 从注解获取任务列表
     *
     * @return
     */
    public static List<Entity> getTaskJobList() {
        List<Entity> list = new ArrayList<>();
        ApplicationContext context = SpringContextUtil.getApplicationContext();
        Map<String, Object> map = context.getBeansWithAnnotation(TaskJob.class);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            TaskJob taskJob = AnnotationUtils.findAnnotation(clazz, TaskJob.class);
            if (taskJob == null) {
                continue;
            }
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(TaskJobMethod.class)) {
                    TaskJobMethod jobMethod = method.getAnnotation(TaskJobMethod.class);
                    if (jobMethod == null) {
                        continue;
                    }
                    Entity jobEntity = new Entity(JobConstants.TABLE_NAME_SYS_TASK_JOB);
                    jobEntity.put("mode", taskJob.mode());
                    jobEntity.put("job_object_name", entry.getKey());
                    jobEntity.put("job_method_name", method.getName());
                    list.add(jobEntity);
                }
            }
        }
        return list;
    }

    /**
     * 保存任务日志
     *
     * @param dataSource
     * @param logEntity
     */
    public static void saveJobExecLog(DataSource dataSource, Entity logEntity) {
        try {
            boolean tableExist = DataSourceUtils.isTableExist(dataSource, JobConstants.TABLE_NAME_SYS_TASK_JOB_EXEC_LOG);
            if (tableExist) {
                if (HlpUtils.isEmpty(logEntity.getTableName())) {
                    logEntity.setTableName(JobConstants.TABLE_NAME_SYS_TASK_JOB_EXEC_LOG);
                }
                Db db = DbUtil.use(dataSource);
                db.insert(logEntity);
            }
        } catch (Exception e) {
            LOGGER.info("保存任务日志到数据库出错：" + JSON.toJSONString(logEntity));
            LOGGER.info(ExceptionUtil.getStackTraceFromException(e));
        }
    }
}
